package cn.b.sky.user.service.impl;

import cn.b.sky.user.dao.OrganizationDao;
import cn.b.sky.user.service.OrganizationService;
import cn.b.sky.user.service.model.Organization;
import cn.b.sky.user.service.model.UserInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("organizationService")
public class OrganizationServiceImpl implements OrganizationService {
  @Resource
  OrganizationDao organizationDao;

  @Override
  public List<Organization> selectRootOrg(String siteCode, boolean isContainLock) {
    return organizationDao.selectRootOrg(siteCode, isContainLock);
  }

  @Override
  public List<Organization> selectOrgByParent(String siteCode, String parentOrganizationCode, boolean isContainLock) {
    return organizationDao.selectOrgByParent(siteCode, parentOrganizationCode, isContainLock);
  }

  @Override
  public List<Organization> selectOrganizationList(String siteCode, boolean isContainLock) {
    List<Organization> menuList = organizationDao.selectRootOrg(siteCode, isContainLock);
    if (menuList != null) {
      for (Organization m : menuList) {
        m.setPath("/");
        getChildren(m, isContainLock);
      }
    }
    return menuList;
  }

  private void getChildren(Organization organization, boolean isContainLock) {
    List<Organization> children = organizationDao.selectOrgByParent(organization.getSiteCode(),
        organization.getOrganizationCode(), isContainLock);
    organization.setChildren(children);
    if (organization.getChildren() != null) {
      for (Organization m : organization.getChildren()) {
        if ("/".equals(organization.getPath())) {
          m.setPath(organization.getPath() + organization.getOrganizationText());
        } else {
          m.setPath(organization.getPath() + "/" + organization.getOrganizationText());
        }
        getChildren(m, isContainLock);
      }
    }
  }

  @Override
  public Organization selectOrganization(String siteCode, String organizationCode) {
    return organizationDao.selectOrganization(siteCode, organizationCode);
  }

  @Override
  public void insertOrganization(Organization organization) {
    organizationDao.insertOrganization(organization);

  }

  @Override
  public void updateOrganization(Organization organization) {
    organizationDao.updateOrganization(organization);

  }

  @Override
  public void deleteOrganization(String siteCode, String organizationCode) {
    organizationDao.deleteOrganization(siteCode, organizationCode);

  }

  @Override
  public List<UserInfo> selectUsersByOrganization(String siteCode, String organizationCode) {
    return organizationDao.selectUsersByOrganization(siteCode, organizationCode);
  }

}
